﻿using System;
using System.Data;
using System.IO;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Services.Exceptions;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class Contact2Student : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!CurrentUser.IsFullAccount || CurrentUser.DeactivatedDate < DateTime.Now)
                Response.Redirect("Profile.aspx?pmv=udpacc");

            Page.CloseMessage(lblMsg);
            if (Page.IsPostBack) return;

            var itemId = new Guid(Request["itid"]);
            var request = StudentRequestServices.GetById(itemId);

            lblStudentName.Text = request.Name;
            lblRequestTitle.Text = request.Title;

            //txtYourName.Text = CurrentUser.Name;
            lblYourEmail.Text = CurrentUser.Email;
            //txtTitle.Text = string.Format("Liên hệ - {0}", request.Title);

            if (!request.IsClosed) return;

            btnContact.Visible = false;
            Page.DisplayMessage(lblMsg, "Học viên này đã chọn được giáo viên. Bạn không thể liên lạc được!", MessageType.Warning);
        }

        protected void BtnContactClick(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;

            try
            {
                var itemId = new Guid(Request["itid"]);
                var stdRequest = StudentRequestServices.GetById(itemId);
                var contactedRequest = new ContactedRequest { Request = stdRequest, Teacher = CurrentUser };

                ContactedRequestServices.AddContactedRequest(contactedRequest);
                SendContactEmail(contactedRequest, txtIntroText.Text);

                Page.DisplayMessage(lblMsg, "Bạn đã liên hệ thành công!", MessageType.Success);
            }
            catch (ObjectAlreadyExistException)
            {
                Page.DisplayMessage(lblMsg, "Bạn đã liên hệ với học viên này rồi!", MessageType.Warning);
            }
        }

        protected void BtnCancelClick(object sender, EventArgs e)
        {
            var itemId = new Guid(Request["itid"]);
            Response.Redirect(string.Format("StudentRequestDetails.aspx?itid={0}", itemId));
        }

        #region Private Methods
        private void SendContactEmail(ContactedRequest contactedRequest, string contactContent)
        {
            string tmpPath = Server.MapPath("mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["Contact2Student"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);
            //subject = subject.Replace("$subjectMail", contactTitle).Replace("$teacherName", contactName);

            //var feedbackUrl = string.Format("{0}/StudentFeedback.aspx?ctreqid={1}", SiteUrl, contactedRequest.ID);
            //var refRequestUrl = string.Format("{0}/StudentRequestDetails.aspx?itid={1}", SiteUrl, contactedRequest.Request.ID);
            var urlToTeacher = string.Format("{0}/TeacherDetails.aspx?itid={1}&ctreqid={2}", SiteUrl, contactedRequest.Teacher.ID, contactedRequest.ID);

            NVelocityBuilder.SetResourcePath(tmpPath);
            var contentMail = NVelocityBuilder.Contact2StudentEmailBuilder(Convert.ToString(rows[0]["Content"]), contactedRequest.Request.Name,
                urlToTeacher, contactContent);

            EmailSender.SendMail(subject, contentMail, contactedRequest.Request.Email);
        }
        #endregion
    }
}
